package com.inspinia.base.dao.pageable;

/**
 * 分页请求对象
 *
 * @author zany@buzheng.org
 */
public class Pageable {
    static final long serialVersionUID = 7280485938848398236L;

    private final int page;
    private final int size;
    private String orderBy;
    private String keyWord;

    /**
     * 是否查询总记录数
     */
    private boolean countable = true;

    /**
     * @param page the page no you want to request, start from 0
     * @param size page size
     */
    public Pageable(int page, int size) {
        this(page, size, true);
    }

    public Pageable(int page, int size, String orderBy,String keyWord) {
        this.page = page;
        this.size = size;
        this.orderBy = orderBy;
        this.keyWord = keyWord;
    }

    public Pageable(int page, boolean countable, int size) {
        this.page = page;
        this.countable = countable;
        this.size = size;
    }

    /**
     * @param page      the page no you want to request, start from 0
     * @param size      page size
     * @param countable whether count total numbers
     */
    public Pageable(int page, int size, boolean countable) {

        if (page < 0) {
            throw new IllegalArgumentException("Page index must not be less than zero!");
        }

        if (size < 0) {
            throw new IllegalArgumentException("Page size must not be less than zero!");
        }

        this.page = page;
        this.size = size;

        this.countable = countable;
    }

    public boolean isCountable() {
        return countable;
    }

    public boolean getCountable() {
        return countable;
    }

    public int getPageSize() {

        return size;
    }

    public String getOrderBy() {
        return orderBy;
    }

    public void setOrderBy(String orderBy) {
        this.orderBy = orderBy;
    }

    public int getPageNumber() {
        return page;
    }

    public int getOffset() {
        return (page - 1) * size;
    }

    public boolean hasPrevious() {
        return page > 0;
    }

    public Pageable next() {
        return new Pageable(page + 1, size);
    }

    public Pageable previousOrFirst() {
        return hasPrevious() ? new Pageable(page - 1, size) : this;
    }

    public Pageable first() {
        return new Pageable(0, size);
    }

    /*
     * (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return String.format("Page request [number: %d, size %d, sort: %s]", page, size);
    }

    public String getKeyWord() {
        return keyWord;
    }

    public void setKeyWord(String keyWord) {
        this.keyWord = keyWord;
    }
}
